// index/pages/dailyPractice/dailyPractice.js
const storageUtil = require('../../../utils/storageUtil');

Page({
  data: {
    // 参与人数
    participantCount: 232,
    
    // 打卡信息
    checkInDays: 3,
    targetDays: 7,
    rewardPoints: 30,
    
    // 当前月份
    currentMonth: '2024年04月',
    
    // 日历数据
    calendar: {
      weekDays: ['一', '二', '三', '四', '五', '六', '日'],
      days: []
    },
    
    // 任务列表
    taskList: [],
    
    // 答题记录列表
    answerRecords: [],
    
    // 题库信息映射
    questionBankMap: {},

    // 加载状态
    loading: false,

    // 接口状态
    apiStatus: {
      checkInRecord: 'unknown', // unknown, success, failed
      tasks: 'unknown',
      participantCount: 'unknown',
      answerRecords: 'unknown' // 新增答题记录状态
    },

    // 后端接口地址
    baseUrl: 'http://localhost:8080'
  },

  onLoad(options) {
    
    this.initCalendar();
    this.loadDailyPracticeData();
    
    // 输出存储状态
    setTimeout(() => {
      
    }, 1000);
  },

  /**
   * 初始化日历
   */
  initCalendar() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;

    this.setData({
      currentMonth: `${year}年${month.toString().padStart(2, '0')}月`
    });

    this.generateCalendarDays(year, month);
  },

  /**
   * 生成日历天数
   */
  generateCalendarDays(year, month) {
    const firstDay = new Date(year, month - 1, 1);
    const lastDay = new Date(year, month, 0);
    const startDate = new Date(firstDay);
    const endDate = new Date(lastDay);

    // 获取上个月末尾的日期
    const prevMonthEnd = new Date(year, month - 1, 0);
    const prevMonthDays = [];
    const firstDayWeek = firstDay.getDay() || 7; // 转换为周一到周日 (1-7)

    for (let i = firstDayWeek - 1; i > 0; i--) {
      const day = prevMonthEnd.getDate() - i + 1;
      prevMonthDays.push({
        day: day,
        type: 'prev',
        active: false,
        uniqueKey: `prev-${day}` // 添加唯一key
      });
    }

    // 获取当前月的日期
    const currentMonthDays = [];
    for (let day = 1; day <= endDate.getDate(); day++) {
      const date = new Date(year, month - 1, day);
      currentMonthDays.push({
        day: day,
        type: 'current',
        active: false,
        date: this.formatDate(date), // 使用格式化函数
        uniqueKey: `current-${day}` // 添加唯一key
      });
    }

    // 获取下个月开头的日期
    const nextMonthDays = [];
    const lastDayWeek = lastDay.getDay() || 7;
    const remainingDays = 7 - lastDayWeek;

    for (let day = 1; day <= remainingDays; day++) {
      const nextMonth = month === 12 ? 1 : month + 1;
      const nextYear = month === 12 ? year + 1 : year;
      const date = new Date(nextYear, nextMonth - 1, day);
      nextMonthDays.push({
        day: day,
        type: 'next',
        active: false,
        uniqueKey: `next-${day}` // 添加唯一key
      });
    }

    const allDays = [...prevMonthDays, ...currentMonthDays, ...nextMonthDays];

    this.setData({
      'calendar.days': allDays
    });
  },

  /**
   * 加载一日一练数据
   */
  loadDailyPracticeData() {
    this.setData({ loading: true });

    // 并行加载所有数据，互不依赖
    Promise.allSettled([
      this.loadCheckInRecord(),
      this.loadTaskList(),
      this.loadParticipantCount(),
      this.loadAnswerRecords() // 答题记录独立运行
    ]).then(() => {
      this.setData({ loading: false });

    });
  },

  /**
   * 加载打卡记录
   */
  loadCheckInRecord() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;

    // 检查存储状态
    const storageStatus = storageUtil.checkStorageStatus();
    

    // 获取token和用户ID
    const token = storageUtil.getToken();
    const userId = storageUtil.getUserId(); // 从storage获取用户ID
    
    // 添加调试信息
    

    if (!token || !userId) {
      
      
      // 尝试从其他可能的键名获取用户信息
      try {
        const allStorage = wx.getStorageInfoSync();

        
        // 尝试获取可能的用户信息
        for (let key of allStorage.keys) {
          if (key.includes('user') || key.includes('User') || key.includes('USER')) {
            const value = wx.getStorageSync(key);

          }
        }
      } catch (e) {
        console.error('获取存储信息失败:', e);
      }
      
      this.setData({
        'apiStatus.checkInRecord': 'failed'
      });
      this.setDefaultCheckInData();
      return Promise.resolve();
    }

    return new Promise((resolve) => {
      // 使用新的接口获取用户练习记录
      wx.request({
        url: `${this.data.baseUrl}/hyg/practice/user/${userId}`,
        method: 'GET',
        header: {
          'content-type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 200) {
            const userPracticeData = res.data.data || {};
    

            this.setData({
              'apiStatus.checkInRecord': 'success'
            });

            // 处理用户练习数据
            this.processUserPracticeData(userPracticeData, year, month);
          } else {
            console.error('获取用户练习记录失败:', res.data);
            this.setData({
              'apiStatus.checkInRecord': 'failed'
            });
            this.setDefaultCheckInData();
          }
          resolve();
        },
        fail: (err) => {
          console.error('获取用户练习记录失败:', err);
          this.setData({
            'apiStatus.checkInRecord': 'failed'
          });
          this.setDefaultCheckInData();
          resolve();
        }
      });
    });
  },

  /**
   * 处理用户练习数据
   */
  processUserPracticeData(userPracticeData, year, month) {
    // 解析用户练习记录
    const practiceRecords = userPracticeData || [];
    
    
    // 统计打卡天数和积分
    let checkInDays = 0;
    const checkInDates = [];
    const practiceTimeMap = {}; // 记录每天的练习时间
    const pointsMap = {}; // 记录每天的积分

    practiceRecords.forEach(record => {
      if (record.practiceDate) {
        // 处理日期格式，确保是 YYYY-MM-DD 格式
        let dateStr = record.practiceDate;
        
        // 如果日期包含时间，只取日期部分
        if (dateStr.includes(' ')) {
          dateStr = dateStr.split(' ')[0];
        }
        
        // 如果日期格式是 YYYY-MM-DD，直接使用
        if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
          if (!checkInDates.includes(dateStr)) {
            checkInDates.push(dateStr);
            checkInDays++;
          }
          
          // 累计每天的练习时间（分钟）
          if (record.studyTime) {
            practiceTimeMap[dateStr] = (practiceTimeMap[dateStr] || 0) + record.studyTime;
          }
          
          // 累计每天的积分
          if (record.pointsAwarded) {
            pointsMap[dateStr] = (pointsMap[dateStr] || 0) + record.pointsAwarded;
          }
        }
      }
    });

    // 计算总积分
    const totalPoints = Object.values(pointsMap).reduce((sum, points) => sum + points, 0);
    
    

    // 更新打卡天数和积分
    this.setData({
      checkInDays: checkInDays,
      rewardPoints: totalPoints
    });

    // 更新日历打卡状态
    this.updateCalendarCheckInStatus(checkInDates, practiceTimeMap);
    
    // 更新任务列表（基于练习记录）
    this.updateTaskListFromPractice(practiceRecords);
  },

  /**
   * 更新日历打卡状态
   */
  updateCalendarCheckInStatus(checkInDates, practiceTimeMap) {
    const days = this.data.calendar.days.map(day => {
      if (day.type === 'current' && day.date) {
        const isCheckedIn = checkInDates.includes(day.date);
        const isToday = this.isToday(day.date);
        const practiceTime = practiceTimeMap[day.date] || 0;

        return {
          ...day,
          active: isCheckedIn,
          status: isCheckedIn ? 'completed' : 'incomplete',
          hasStar: isToday && isCheckedIn,
          practiceTime: practiceTime // 添加练习时间信息
        };
      }
      return day;
    });

    this.setData({
      'calendar.days': days
    });
    
    
  },

  /**
   * 格式化日期为 YYYY-MM-DD 格式
   */
  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  /**
   * 判断是否为今天
   */
  isToday(dateString) {
    const today = new Date();
    const date = new Date(dateString);
    return today.getFullYear() === date.getFullYear() &&
           today.getMonth() === date.getMonth() &&
           today.getDate() === date.getDate();
  },

  /**
   * 设置默认打卡数据
   */
  setDefaultCheckInData() {
    // 设置一些默认的打卡数据用于演示
    const today = new Date();
    const todayString = this.formatDate(today);

    const days = this.data.calendar.days.map(day => {
      if (day.type === 'current' && day.date) {
        const isToday = this.isToday(day.date);
        const isCheckedIn = Math.random() > 0.3; // 随机设置一些打卡状态

        return {
          ...day,
          active: isCheckedIn,
          status: isCheckedIn ? 'completed' : 'incomplete',
          hasStar: isToday && isCheckedIn
        };
      }
      return day;
    });

    this.setData({
      'calendar.days': days,
      checkInDays: 3,
      rewardPoints: 30
    });
  },

  /**
   * 加载任务列表
   */
  loadTaskList() {
    // 获取token
    const token = storageUtil.getToken();

    if (!token) {
      this.setData({
        'apiStatus.tasks': 'failed'
      });
      this.setDefaultTaskData();
      return Promise.resolve();
    }

    return new Promise((resolve) => {
      // 由于后端没有任务列表接口，我们使用打卡记录来生成任务
      // 或者直接使用默认数据
      this.setData({
        'apiStatus.tasks': 'success'
      });
      this.setDefaultTaskData();
      resolve();
    });
  },

  /**
   * 基于练习记录更新任务列表
   */
  updateTaskListFromPractice(practiceRecords) {
    // 按科目分组练习记录（这里暂时按日期分组，因为没有科目信息）
    const dateGroups = {};
    
    practiceRecords.forEach(record => {
      if (record.practiceDate) {
        let dateStr = record.practiceDate;
        
        // 如果日期包含时间，只取日期部分
        if (dateStr.includes(' ')) {
          dateStr = dateStr.split(' ')[0];
        }
        
        if (!dateGroups[dateStr]) {
          dateGroups[dateStr] = {
            records: [],
            totalQuestions: 0,
            totalTime: 0,
            totalPoints: 0,
            lastPracticeDate: null
          };
        }
        
        dateGroups[dateStr].records.push(record);
        dateGroups[dateStr].totalQuestions += record.questionCount || 0;
        dateGroups[dateStr].totalTime += record.studyTime || 0;
        dateGroups[dateStr].totalPoints += record.pointsAwarded || 0;
        
        // 更新最后练习日期
        if (record.practiceDate) {
          const practiceDate = new Date(record.practiceDate);
          if (!dateGroups[dateStr].lastPracticeDate || 
              practiceDate > new Date(dateGroups[dateStr].lastPracticeDate)) {
            dateGroups[dateStr].lastPracticeDate = record.practiceDate;
          }
        }
      }
    });

    // 转换为任务列表格式
    const taskList = Object.keys(dateGroups).map((dateStr, index) => {
      const group = dateGroups[dateStr];
      const today = new Date();
      const lastPractice = group.lastPracticeDate ? new Date(group.lastPracticeDate) : null;
      
      // 判断任务状态
      let status = 'notStarted';
      let statusText = '未练';
      
      if (lastPractice) {
        const daysDiff = Math.floor((today - lastPractice) / (1000 * 60 * 60 * 24));
        if (daysDiff === 0) {
          status = 'completed';
          statusText = '已练';
        } else if (daysDiff <= 3) {
          status = 'incomplete';
          statusText = '需复习';
        }
      }

      // 格式化日期显示
      const date = new Date(dateStr);
      const month = date.getMonth() + 1;
      const day = date.getDate();

      return {
        id: index + 1,
        title: `${month}月${day}日练习`,
        status: status,
        statusText: statusText,
        questionCount: group.totalQuestions,
        completedCount: group.records.length,
        lastPracticeDate: group.lastPracticeDate,
        totalPracticeTime: group.totalTime,
        totalPoints: group.totalPoints,
        practiceDate: dateStr
      };
    });

    // 按日期排序，最新的在前面
    taskList.sort((a, b) => new Date(b.practiceDate) - new Date(a.practiceDate));

    // 如果没有练习记录，使用默认任务
    if (taskList.length === 0) {
      this.setDefaultTaskData();
    } else {
      this.setData({
        taskList: taskList
      });
    }
    
    console.log('生成的任务列表:', taskList);
  },

  /**
   * 设置默认任务数据
   */
  setDefaultTaskData() {
    const defaultTasks = [
      {
        id: 1,
        title: '生物化学-12/21',
        status: 'completed',
        statusText: '已练',
        questionCount: 20,
        completedCount: 30
      },
      {
        id: 2,
        title: '生物微生物-12/21',
        status: 'incomplete',
        statusText: '未完成',
        questionCount: 20,
        completedCount: 30
      },
      {
        id: 3,
        title: '生物细胞学-12/21',
        status: 'notStarted',
        statusText: '未练',
        questionCount: 20,
        completedCount: 0
      }
    ];

    this.setData({
      taskList: defaultTasks
    });
  },

  /**
   * 加载参与人数
   */
  loadParticipantCount() {
    // 获取token
    const token = storageUtil.getToken();

    if (!token) {
      this.setData({
        'apiStatus.participantCount': 'failed'
      });
      this.setData({
        participantCount: 232
      });
      return Promise.resolve();
    }

    return new Promise((resolve) => {
      // 使用后端的用户统计接口
      wx.request({
        url: `${this.data.baseUrl}/hyg/practice/list`,
        method: 'GET',
        data: {
          pageNum: 1,
          pageSize: 1 // 只需要总数
        },
        header: {
          'content-type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 200) {
            const total = res.data.total || 0;


            this.setData({
              'apiStatus.participantCount': 'success',
              participantCount: total > 0 ? total : 232
            });
          } else {
            console.error('获取参与人数失败:', res.data);
            this.setData({
              'apiStatus.participantCount': 'failed',
              participantCount: 232
            });
          }
          resolve();
        },
        fail: (err) => {
          console.error('获取参与人数失败:', err);
          this.setData({
            'apiStatus.participantCount': 'failed',
            participantCount: 232
          });
          resolve();
        }
      });
    });
  },

  /**
   * 加载答题记录（独立运行，不依赖其他功能）
   */
  loadAnswerRecords() {
    const token = storageUtil.getToken();
    const userId = storageUtil.getUserId();

    if (!token || !userId) {
      this.setData({
        'apiStatus.answerRecords': 'failed'
      });
      // 即使没有用户信息，也显示空状态，不影响其他功能
      this.setData({
        answerRecords: []
      });
      return Promise.resolve();
    }

    return new Promise((resolve) => {
      wx.request({
        url: `${this.data.baseUrl}/wjq/answerrecord/list`,
        method: 'GET',
        header: {
          'content-type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        data: {
          userId: userId
        },
        success: (res) => {
          console.log('答题记录API响应:', res);
          
          if (res.statusCode === 200 && res.data.code === 200) {
            // 使用rows字段获取答题记录数组
            const allAnswerRecords = res.data.rows || res.data.data || [];

            // 过滤今天的答题记录
            const todayRecords = this.filterTodayRecords(allAnswerRecords);
            
            console.log('所有答题记录数量:', allAnswerRecords.length);
            console.log('今天的答题记录数量:', todayRecords.length);
            
            // 输出每条记录的详细信息
            todayRecords.forEach((record, index) => {
              console.log(`今天答题记录 ${index + 1}:`, {
                id: record.id,
                bankId: record.bank_id || record.bankId,
                totalCount: record.total_count || record.totalCount,
                correctList: record.correct_list || record.correctList,
                wrongList: record.wrong_list || record.wrongList,
                unansweredList: record.unanswered_list || record.unansweredList,
                timeUsed: record.time_used || record.timeUsed,
                recordType: record.record_type || record.recordType,
                createTime: record.create_time || record.createTime,
                userId: record.user_id || record.userId,
                完整记录: record
              });
            });
            
            this.setData({
              'apiStatus.answerRecords': 'success'
            });

            // 处理答题记录，获取题库信息
            this.processAnswerRecords(todayRecords);
          } else {
            console.error('获取答题记录失败:', res.data);
            console.error('错误详情:', {
              statusCode: res.statusCode,
              code: res.data.code,
              message: res.data.msg || res.data.message,
              data: res.data.data
            });
            this.setData({
              'apiStatus.answerRecords': 'failed',
              answerRecords: []
            });
          }
          resolve();
        },
        fail: (err) => {
          console.error('获取答题记录请求失败:', err);
          console.error('错误详情:', {
            errMsg: err.errMsg,
            statusCode: err.statusCode,
            data: err.data
          });
          this.setData({
            'apiStatus.answerRecords': 'failed',
            answerRecords: []
          });
          resolve();
        }
      });
    });
  },

  /**
   * 过滤今天的答题记录
   */
  filterTodayRecords(allRecords) {
    if (!allRecords || allRecords.length === 0) {
      return [];
    }

    const today = new Date();
    const todayStr = today.toISOString().split('T')[0]; // 格式：YYYY-MM-DD
    
    console.log('今天的日期:', todayStr);
    
    const todayRecords = allRecords.filter(record => {
      if (!record.createTime) {
        return false;
      }
      
      // 处理不同的日期格式
      let recordDateStr = record.createTime;
      
      // 如果包含时间，只取日期部分
      if (recordDateStr.includes(' ')) {
        recordDateStr = recordDateStr.split(' ')[0];
      }
      
      // 如果包含T，说明是ISO格式
      if (recordDateStr.includes('T')) {
        recordDateStr = recordDateStr.split('T')[0];
      }
      
      console.log(`记录日期: ${recordDateStr}, 今天日期: ${todayStr}, 是否匹配: ${recordDateStr === todayStr}`);
      
      return recordDateStr === todayStr;
    });
    
    return todayRecords;
  },

  /**
   * 处理答题记录，获取题库信息
   */
  processAnswerRecords(answerRecords) {
    if (!answerRecords || answerRecords.length === 0) {
      return;
    }

    // 提取所有唯一的题库ID - 使用bank_id字段
    const questionBankIds = [...new Set(answerRecords.map(record => record.bank_id || record.bankId).filter(id => id))];
    
    if (questionBankIds.length === 0) {
      // 即使没有题库ID，也显示答题记录
      this.updateAnswerRecordsWithBankInfo(answerRecords, {});
      return;
    }

    // 批量获取题库信息
    this.fetchQuestionBanks(questionBankIds, answerRecords);
  },

  /**
   * 批量获取题库信息
   */
  fetchQuestionBanks(questionBankIds, answerRecords) {
    const token = storageUtil.getToken();
    const questionBankMap = {};
    let completedCount = 0;

    questionBankIds.forEach(bankId => {
      
      wx.request({
        url: `${this.data.baseUrl}/fk/question_bank/${bankId}`,
        method: 'GET',
        header: {
          'content-type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {

          
          if (res.statusCode === 200 && res.data.code === 200) {
            const questionBank = res.data.data;
            questionBankMap[bankId] = questionBank;

          } else {
            console.error(`获取题库 ${bankId} 信息失败:`, res.data);
            console.error(`题库 ${bankId} 错误详情:`, {
              statusCode: res.statusCode,
              code: res.data.code,
              message: res.data.msg || res.data.message,
              data: res.data.data
            });
            questionBankMap[bankId] = { name: '未知题库', subject: '未知科目' };
          }
        },
        fail: (err) => {
          console.error(`获取题库 ${bankId} 信息请求失败:`, err);
          console.error(`题库 ${bankId} 错误详情:`, {
            errMsg: err.errMsg,
            statusCode: err.statusCode,
            data: err.data
          });
          questionBankMap[bankId] = { name: '未知题库', subject: '未知科目' };
        },
        complete: () => {
          completedCount++;
          
          // 当所有题库信息都获取完成后，更新数据
          if (completedCount === questionBankIds.length) {
            this.updateAnswerRecordsWithBankInfo(answerRecords, questionBankMap);
          }
        }
      });
    });
  },

  /**
   * 更新答题记录，添加题库信息
   */
  updateAnswerRecordsWithBankInfo(answerRecords, questionBankMap) {
    const enrichedRecords = answerRecords.map((record, index) => {
      const questionBank = questionBankMap[record.bank_id || record.bankId] || {};
      
      // 解析题目ID列表的函数
      const parseQuestionIds = (listStr) => {
        if (!listStr) return [];
        
        try {
          // 处理格式：["[\"q_0\"","\"q_1\"]"] 或 ["q_0","q_1"]
          let cleanStr = listStr;
          
          // 如果是嵌套的JSON字符串，先解析外层
          if (cleanStr.startsWith('[') && cleanStr.endsWith(']')) {
            try {
              const parsed = JSON.parse(cleanStr);
              if (Array.isArray(parsed) && parsed.length > 0) {
                // 如果内层还是字符串，继续解析
                if (typeof parsed[0] === 'string' && parsed[0].startsWith('[')) {
                  const innerParsed = JSON.parse(parsed[0]);
                  return Array.isArray(innerParsed) ? innerParsed : [];
                }
                return parsed;
              }
            } catch (e) {
              console.warn('解析外层JSON失败:', e);
            }
          }
          
          // 尝试直接解析
          try {
            const parsed = JSON.parse(cleanStr);
            return Array.isArray(parsed) ? parsed : [];
          } catch (e) {
            console.warn('直接解析JSON失败:', e);
          }
          
          // 如果都失败了，尝试字符串分割
          return cleanStr.split(',').map(id => id.trim().replace(/"/g, '')).filter(id => id);
        } catch (e) {
          console.error('解析题目ID列表失败:', e, '原始数据:', listStr);
          return [];
        }
      };
      
      // 计算正确率
      const totalQuestions = record.total_count || record.totalCount || 0;
      const correctCount = parseQuestionIds(record.correct_list || record.correctList).length;
      const wrongCount = parseQuestionIds(record.wrong_list || record.wrongList).length;
      const unansweredCount = parseQuestionIds(record.unanswered_list || record.unansweredList).length;
      
      const enrichedRecord = {
        ...record,
        questionBankName: questionBank.name || '未知题库',
        questionBankSubject: questionBank.subject || '未知科目',
        // 格式化答题时间
        answerTimeFormatted: this.formatAnswerTime(record.createTime),
        // 使用timeUsedStr作为答题用时
        answerDuration: record.timeUsedStr || null,
        // 计算正确率
        correctRate: totalQuestions > 0 ? Math.round((correctCount / totalQuestions) * 100) : 0,
        // 添加计算后的字段
        totalQuestions: totalQuestions,
        correctCount: correctCount,
        wrongCount: wrongCount,
        unansweredCount: unansweredCount
      };
      

      return enrichedRecord;
    });

    // 按答题时间排序，最新的在前面
    enrichedRecords.sort((a, b) => {
      const timeA = new Date(a.createTime);
      const timeB = new Date(b.createTime);
      return timeB - timeA;
    });



    this.setData({
      answerRecords: enrichedRecords,
      questionBankMap: questionBankMap
    });
    

  },

  /**
   * 格式化答题时间
   */
  formatAnswerTime(timeString) {
    if (!timeString) return '未知时间';
    
    const date = new Date(timeString);
    const now = new Date();
    const diffTime = now - date;
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays === 0) {
      return '今天';
    } else if (diffDays === 1) {
      return '昨天';
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    }
  },

  /**
   * 计算答题用时
   */
  calculateAnswerDuration(startTime, endTime) {
    if (!startTime || !endTime) return null;
    
    const start = new Date(startTime);
    const end = new Date(endTime);
    const duration = end - start;
    
    const minutes = Math.floor(duration / (1000 * 60));
    const seconds = Math.floor((duration % (1000 * 60)) / 1000);
    
    if (minutes > 0) {
      return `${minutes}分${seconds}秒`;
    } else {
      return `${seconds}秒`;
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  // 跳转到排行榜
  goToRanking() {
    wx.navigateTo({
      url: '/index/pages/dailyPracticeRankingList/dailyPracticeRankingList'
    });
  },

  // 开始练习
  startPractice(e) {
    const taskId = e.currentTarget.dataset.id;

    wx.showToast({
      title: '开始练习',
      icon: 'none'
    });

    // 这里可以跳转到练习页面
    // wx.navigateTo({
    //   url: `/index/pages/practice/practice?taskId=${taskId}`
    // });
  },

  // 邀请好友
  inviteFriends() {
    wx.showToast({
      title: '邀请功能开发中',
      icon: 'none'
    })
  },

  // 查看排行榜
  viewLeaderboard() {
    wx.navigateTo({
      url: '/index/pages/dailyPracticeRankingList/dailyPracticeRankingList',
      // 跳转失败时的回调
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({
          title: '跳转失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  // 添加助教
  addAssistant() {
    wx.navigateTo({
      url: '/index/pages/addTeacher/addTeacher'
    });
  },

  /**
   * 日历日期点击事件
   */
  onCalendarDayTap(e) {
    const dayData = e.currentTarget.dataset.day;
    
    if (dayData.type !== 'current') {
      return; // 只能点击当前月的日期
    }

    const today = new Date();
    const clickDate = new Date(dayData.date);
    
    // 只能打卡今天或之前的日期
    if (clickDate > today) {
      wx.showToast({
        title: '不能打卡未来日期',
        icon: 'none'
      });
      return;
    }

    // 如果已经打卡，显示练习详情
    if (dayData.active) {
      this.showPracticeDetail(dayData);
      return;
    }

    // 执行打卡
    this.performCheckIn(dayData);
  },

  /**
   * 执行打卡
   */
  performCheckIn(dayData) {
    const token = storageUtil.getToken();
    const userId = storageUtil.getUserId();

    if (!token || !userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '打卡中...',
      mask: true
    });

    // 这里可以调用打卡接口
    // 暂时模拟打卡成功
    setTimeout(() => {
      wx.hideLoading();
      
      // 更新日历状态
      const days = this.data.calendar.days.map(day => {
        if (day.uniqueKey === dayData.uniqueKey) {
          return {
            ...day,
            active: true,
            status: 'completed',
            hasStar: this.isToday(day.date)
          };
        }
        return day;
      });

      this.setData({
        'calendar.days': days,
        checkInDays: this.data.checkInDays + 1
      });

      wx.showToast({
        title: '打卡成功！',
        icon: 'success'
      });
    }, 1000);
  },

  /**
   * 显示练习详情
   */
  showPracticeDetail(dayData) {
    const practiceTime = dayData.practiceTime || 0;
    const dateStr = dayData.date;
    
    // 构建练习报告数据
    const reportData = {
      total: 0, // 这里可以根据实际数据填充
      correct: 0,
      wrong: 0,
      unanswered: 0,
      correctRate: 0,
      totalTime: `${practiceTime}分钟`,
      completeTime: dateStr,
      questionBankName: '一日一练',
      questionBankSubject: '综合练习',
      recordType: '每日练习',
      score: 0,
      timeUsed: practiceTime * 60, // 转换为秒
      timeUsedStr: `${practiceTime}分钟`
    };
    
    // 保存练习报告到本地存储
    try {
      const storageKey = `answerReport_dailyPractice_${dateStr}`;
      wx.setStorageSync(storageKey, reportData);
      
    } catch (e) {
      console.error('保存练习报告失败:', e);
    }
    
    // 跳转到答题详情页面
    wx.navigateTo({
      url: `/index/pages/answerReport/answerReport?reportData=${encodeURIComponent(JSON.stringify(reportData))}`,
      success: () => {
        console.log('跳转到答题详情页面成功');
      },
      fail: (err) => {
        console.error('跳转到答题详情页面失败:', err);
        // 如果跳转失败，显示弹窗作为备选方案
        wx.showModal({
          title: `${dateStr} 练习详情`,
          content: `练习时间: ${practiceTime}分钟\n状态: 已完成`,
          showCancel: false,
          confirmText: '确定'
        });
      }
    });
  },

  /**
   * 独立刷新答题记录
   */
  refreshAnswerRecords() {
    this.setData({
      'apiStatus.answerRecords': 'unknown'
    });
    
    wx.showLoading({
      title: '刷新答题记录中...',
      mask: true
    });
    
    this.loadAnswerRecords().then(() => {
      wx.hideLoading();
      wx.showToast({
        title: '答题记录刷新完成',
        icon: 'success'
      });
    }).catch(() => {
      wx.hideLoading();
      wx.showToast({
        title: '刷新失败，请重试',
        icon: 'none'
      });
    });
  },

  /**
   * 点击答题记录项查看详情
   */
  onAnswerRecordTap(e) {
    const record = e.currentTarget.dataset.record;
    
    // 构建答题报告数据
    const reportData = {
      total: record.totalQuestions || 0,
      correct: record.correctCount || 0,
      wrong: record.wrongCount || 0,
      unanswered: record.unansweredCount || 0,
      correctRate: record.correctRate || 0,
      totalTime: record.answerDuration || '未知',
      completeTime: record.answerTimeFormatted || '未知',
      questionBankName: record.questionBankName || '未知题库',
      questionBankSubject: record.questionBankSubject || '未知科目',
      recordType: record.record_type || record.recordType || '练习记录',
      score: record.score || 0,
      timeUsed: record.time_used || record.timeUsed || 0,
      timeUsedStr: record.timeUsedStr || '',
      // 新增：题库ID，用于解析功能
      questionBankId: record.bank_id || record.bankId || null
    };
    
    // 计算未答题数
    const unanswered = reportData.total - reportData.correct - reportData.wrong;
    reportData.unanswered = Math.max(0, unanswered);
    
    // 构建题目ID映射（用于解析功能）
    const questionIdMap = {};
    
    // 解析题目ID列表的函数
    const parseQuestionIds = (listStr) => {
      if (!listStr) return [];
      
      try {
        // 处理格式：["[\"q_0\"","\"q_1\"]"] 或 ["q_0","q_1"]
        let cleanStr = listStr;
        
        // 如果是嵌套的JSON字符串，先解析外层
        if (cleanStr.startsWith('[') && cleanStr.endsWith(']')) {
          try {
            const parsed = JSON.parse(cleanStr);
            if (Array.isArray(parsed) && parsed.length > 0) {
              // 如果内层还是字符串，继续解析
              if (typeof parsed[0] === 'string' && parsed[0].startsWith('[')) {
                const innerParsed = JSON.parse(parsed[0]);
                return Array.isArray(innerParsed) ? innerParsed : [];
              }
              return parsed;
            }
          } catch (e) {
            console.warn('解析外层JSON失败:', e);
          }
        }
        
        // 尝试直接解析
        try {
          const parsed = JSON.parse(cleanStr);
          return Array.isArray(parsed) ? parsed : [];
        } catch (e) {
          console.warn('直接解析JSON失败:', e);
        }
        
        // 如果都失败了，尝试字符串分割
        return cleanStr.split(',').map(id => id.trim().replace(/"/g, '')).filter(id => id);
      } catch (e) {
        console.error('解析题目ID列表失败:', e, '原始数据:', listStr);
        return [];
      }
    };
    
    // 收集所有真实的题目ID
    const correctIds = parseQuestionIds(record.correct_list || record.correctList);
    const wrongIds = parseQuestionIds(record.wrong_list || record.wrongList);
    const unansweredIds = parseQuestionIds(record.unanswered_list || record.unansweredList);
    
    const allQuestionIds = [...correctIds, ...wrongIds, ...unansweredIds];
    
    console.log('解析的题目ID:', {
      correctIds,
      wrongIds,
      unansweredIds,
      allQuestionIds
    });
    
    // 构建索引到题目ID的映射
    allQuestionIds.forEach((questionId, index) => {
      questionIdMap[index] = questionId;
    });
    
    reportData.questionIdMap = questionIdMap;
    
    // 构建增强答题状态（用于解析功能）
    const enhancedAnswerStatus = {};
    
    // 处理正确题目列表
    correctIds.forEach((questionId, index) => {
      enhancedAnswerStatus[index] = {
        status: 'correct',
        questionId: questionId, // 使用真实的题目ID
        userAnswer: 'A', // 这里需要从实际数据中获取
        correctAnswer: 'A', // 这里需要从实际数据中获取
        timestamp: Date.now() - (correctIds.length - index) * 60000, // 模拟时间戳
        isCorrect: true
      };
    });
    
    // 处理错误题目列表
    wrongIds.forEach((questionId, index) => {
      const actualIndex = reportData.correct + index; // 错误题目的实际索引
      enhancedAnswerStatus[actualIndex] = {
        status: 'wrong',
        questionId: questionId, // 使用真实的题目ID
        userAnswer: 'B', // 这里需要从实际数据中获取
        correctAnswer: 'A', // 这里需要从实际数据中获取
        timestamp: Date.now() - (wrongIds.length - index) * 60000, // 模拟时间戳
        isCorrect: false
      };
    });
    
    // 处理未答题目列表
    unansweredIds.forEach((questionId, index) => {
      const actualIndex = reportData.correct + reportData.wrong + index; // 未答题目的实际索引
      enhancedAnswerStatus[actualIndex] = {
        status: 'unanswered',
        questionId: questionId, // 使用真实的题目ID
        userAnswer: null,
        correctAnswer: 'A', // 这里需要从实际数据中获取
        timestamp: Date.now() - (unansweredIds.length - index) * 60000, // 模拟时间戳
        isCorrect: false
      };
    });
    
    reportData.enhancedAnswerStatus = enhancedAnswerStatus;
    
    console.log('构建的完整答题报告数据:', reportData);
    
    // 保存答题报告到本地存储
    try {
      const storageKey = `answerReport_${record.bankId || 'dailyPractice'}`;
      wx.setStorageSync(storageKey, reportData);

    } catch (e) {
      console.error('保存答题报告失败:', e);
    }
    
    console.log('构建的完整答题报告数据:', reportData);
    console.log('数据详情:', {
      总题数: reportData.total,
      答对: reportData.correct,
      答错: reportData.wrong,
      未答: reportData.unanswered,
      正确率: reportData.correctRate + '%',
      答题用时: reportData.totalTime,
      完成时间: reportData.completeTime,
      题库名称: reportData.questionBankName,
      题库ID: reportData.questionBankId,
      增强答题状态数量: Object.keys(reportData.enhancedAnswerStatus).length,
      题目ID映射数量: Object.keys(reportData.questionIdMap).length
    });
    
    // 跳转到答题报告页面
    wx.navigateTo({
      url: `/index/pages/answerReport/answerReport?reportData=${encodeURIComponent(JSON.stringify(reportData))}`,
      success: () => {
        console.log('跳转到答题报告页面成功');
        wx.showToast({
          title: '跳转成功',
          icon: 'success',
          duration: 1500
        });
      },
      fail: (err) => {
        console.error('跳转到答题报告页面失败:', err);
        // 如果跳转失败，显示弹窗作为备选方案
        let content = `题库: ${record.questionBankName}\n`;
        content += `科目: ${record.questionBankSubject}\n`;
        content += `答题时间: ${record.answerTimeFormatted}\n`;
        content += `题目总数: ${record.totalQuestions || 0}\n`;
        content += `正确数量: ${record.correctCount || 0}\n`;
        content += `正确率: ${record.correctRate || 0}%\n`;
        
        if (record.answerDuration) {
          content += `答题用时: ${record.answerDuration}\n`;
        }
        
        if (record.score !== undefined) {
          content += `得分: ${record.score}\n`;
        }
        
        content += `状态: ${record.status === 'completed' ? '已完成' : '进行中'}`;
        
        wx.showModal({
          title: '答题详情',
          content: content,
          showCancel: false,
          confirmText: '确定'
        });
      }
    });
  },

  /**
   * 显示答题记录数据（用于调试）
   */
  showAnswerRecordsData() {
    const answerRecords = this.data.answerRecords;
    const questionBankMap = this.data.questionBankMap;
    const apiStatus = this.data.apiStatus.answerRecords;
    
    let content = `API状态: ${apiStatus}\n`;
    content += `答题记录数量: ${answerRecords.length}\n`;
    content += `题库映射数量: ${Object.keys(questionBankMap).length}\n\n`;
    
    if (answerRecords.length > 0) {
      content += '答题记录详情:\n';
      answerRecords.forEach((record, index) => {
        content += `${index + 1}. ID: ${record.id}\n`;
        content += `   题库: ${record.questionBankName}\n`;
        content += `   科目: ${record.questionBankSubject}\n`;
        content += `   题目数: ${record.totalQuestions || 0}\n`;
        content += `   正确数: ${record.correctCount || 0}\n`;
        content += `   正确率: ${record.correctRate || 0}%\n`;
        content += `   得分: ${record.score || 0}\n`;
        content += `   状态: ${record.status || '未知'}\n`;
        content += `   时间: ${record.answerTimeFormatted || '未知'}\n\n`;
      });
    } else {
      content += '暂无答题记录数据';
    }
    
    wx.showModal({
      title: '答题记录数据',
      content: content,
      showCancel: false,
      confirmText: '确定'
    });
  },

  /**
   * 手动设置用户信息（用于测试）
   */
  setTestUserInfo() {
    // 模拟用户信息
    const testUserInfo = {
      id: '12345',
      userId: '12345',
      username: 'testuser',
      token: 'test-token-12345',
      accessToken: 'test-access-token-12345'
    };
    
    // 存储到本地
    storageUtil.setUserInfo(testUserInfo);
    storageUtil.setToken(testUserInfo.token);
    
    
    
    wx.showToast({
      title: '测试用户信息已设置',
      icon: 'success'
    });
    
    // 重新加载数据
    setTimeout(() => {
      this.loadDailyPracticeData();
    }, 1000);
  },

  /**
   * 显示存储状态（用于调试）
   */
  showStorageStatus() {
    const status = storageUtil.checkStorageStatus();
    
    let content = `存储键数量: ${status.totalKeys}\n`;
    content += `用户信息存在: ${status.userInfoExists}\n`;
    content += `Token存在: ${status.tokenExists}\n`;
    
    if (status.userInfoKeys.length > 0) {
      content += `用户信息字段: ${status.userInfoKeys.join(', ')}\n`;
    }
    
    if (status.allKeys.length > 0) {
      content += `所有存储键: ${status.allKeys.join(', ')}`;
    }
    
    wx.showModal({
      title: '存储状态',
      content: content,
      showCancel: false,
      confirmText: '确定'
    });
  }
})